<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Html5,WebWorker," />





  <link rel="alternate" href="/atom.xml" title="OBKoro1's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="我们都知道，JavaScript 是单线程的，在同一时刻只能处理一个任务，我们会通过 setTimeout()、setInterval()、ajax 和事件处理程序等技术模拟“并行”。但都不是真正意义上的并行: Web Worker 是 HTML5 标准的一部分，这一规范定义了一套 API，它允许一段 JavaScript 程序运行在主线程之外的另外一个线程中。 这在很大程度上利用了现在不断升级">
<meta name="keywords" content="Html5,WebWorker">
<meta property="og:type" content="article">
<meta property="og:title" content="前端er来学习一下webWorker吧">
<meta property="og:url" content="http://yoursite.com/2018/11/28/前端er来学习一下webWorker吧/index.html">
<meta property="og:site_name" content="OBKoro1&#39;s Blog">
<meta property="og:description" content="我们都知道，JavaScript 是单线程的，在同一时刻只能处理一个任务，我们会通过 setTimeout()、setInterval()、ajax 和事件处理程序等技术模拟“并行”。但都不是真正意义上的并行: Web Worker 是 HTML5 标准的一部分，这一规范定义了一套 API，它允许一段 JavaScript 程序运行在主线程之外的另外一个线程中。 这在很大程度上利用了现在不断升级">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rColy1fxko2ichsjj30xc0g5412.jpg?raw=true">
<meta property="og:updated_time" content="2019-07-20T06:55:39.065Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="前端er来学习一下webWorker吧">
<meta name="twitter:description" content="我们都知道，JavaScript 是单线程的，在同一时刻只能处理一个任务，我们会通过 setTimeout()、setInterval()、ajax 和事件处理程序等技术模拟“并行”。但都不是真正意义上的并行: Web Worker 是 HTML5 标准的一部分，这一规范定义了一套 API，它允许一段 JavaScript 程序运行在主线程之外的另外一个线程中。 这在很大程度上利用了现在不断升级">
<meta name="twitter:image" content="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rColy1fxko2ichsjj30xc0g5412.jpg?raw=true">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/11/28/前端er来学习一下webWorker吧/"/>





  <title>前端er来学习一下webWorker吧 | OBKoro1's Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?64d57d0b926bbd27431daa89d2e0a76b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">OBKoro1's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-前端算法">
          <a href="/arithmetic/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            前端算法
          </a>
        </li>
      
        
        <li class="menu-item menu-item-博客最新更新">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            博客最新更新
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/11/28/前端er来学习一下webWorker吧/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="OBKoro1">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/hand1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="OBKoro1's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">前端er来学习一下webWorker吧</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-28T19:27:55+08:00">
                2018-11-28
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/js/" itemprop="url" rel="index">
                    <span itemprop="name">js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/11/28/前端er来学习一下webWorker吧/" class="leancloud_visitors" data-flag-title="前端er来学习一下webWorker吧">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,478 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  9分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rColy1fxko2ichsjj30xc0g5412.jpg?raw=true" alt=""></p>
<p>我们都知道，JavaScript 是单线程的，在同一时刻只能处理一个任务，我们会通过 setTimeout()、setInterval()、ajax 和事件处理程序等技术模拟“并行”。但都不是真正意义上的并行:</p>
<p>Web Worker 是 HTML5 标准的一部分，这一规范定义了一套 API，它允许一段 JavaScript 程序运行在主线程之外的另外一个线程中。</p>
<p>这在很大程度上利用了现在不断升级的电脑计算能力：能够在同一时间平行处理两个任务。</p>
<a id="more"></a>
<blockquote>
<p>游泳、健身了解一下：<a href="http://obkoro1.com/" target="_blank" rel="noopener">博客</a>、<a href="http://obkoro1.com/web_accumulate/accumulate/" target="_blank" rel="noopener">前端积累文档</a>、<a href="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1631b6f52f7e7015.jpeg?raw=true" target="_blank" rel="noopener">公众号</a>、<a href="https://github.com/OBKoro1" target="_blank" rel="noopener">GitHub</a></p>
</blockquote>
<h3 id="场景"><a href="#场景" class="headerlink" title="场景"></a>场景</h3><p><strong>当我们有些任务需要花费大量的时间，进行复杂的运算</strong>，就会导致页面卡死：用户点击页面需要很长的时间才能响应，因为前面的任务还未完成，后面的任务只能排队等待。对用户来说，这样的体验无疑是糟糕的，web worker 就是为了解决这种花费大量时间的复杂运算而诞生的！</p>
<h3 id="WebWorker-的作用：创建-worker-线程"><a href="#WebWorker-的作用：创建-worker-线程" class="headerlink" title="WebWorker 的作用：创建 worker 线程"></a>WebWorker 的作用：创建 worker 线程</h3><p>WebWorker 允许在主线程之外再创建一个 worker 线程，<strong>在主线程执行任务的同时，worker 线程也可以在后台执行它自己的任务，互不干扰</strong>。</p>
<p>这样就让 JS 变成多线程的环境了，我们可以把高延迟、花费大量时间的运算，分给 worker 线程，最后再把结果返回给主线程就可以了，因为时间花费多的任务被 web worker 承担了，主线程就会很流畅了！</p>
<hr>
<h2 id="主线程"><a href="#主线程" class="headerlink" title="主线程"></a>主线程</h2><h3 id="我们先来看一下栗子："><a href="#我们先来看一下栗子：" class="headerlink" title="我们先来看一下栗子："></a>我们先来看一下栗子：</h3><p><a href="https://codepen.io/OBKoro1/pen/JevMZY?editors=1000" target="_blank" rel="noopener">codepen</a>,这里我写了一个 class，里面有详细注释，可以参考一下。</p>
<h3 id="创建-worker-对象："><a href="#创建-worker-对象：" class="headerlink" title="创建 worker 对象："></a>创建 worker 对象：</h3><p>主线程调用<code>new Worker()</code>构造函数，新建一个 worker 线程，构造函数的参数是一个 url，生成这个 url 的方法有两种：</p>
<ol>
<li><p>脚本文件：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> worker = <span class="keyword">new</span> Worker(<span class="string">'https://~.js'</span>);</span><br></pre></td></tr></table></figure>
<p>因为 worker 的两个限制：</p>
<ol>
<li><p><strong>分配给 Worker 线程运行的脚本文件，必须与主线程的脚本文件同源</strong>。</p>
</li>
<li><p><strong>worker 不能读取本地的文件</strong>(不能打开本机的文件系统<code>file://</code>)，它所加载的脚本必须来自网络。</p>
</li>
</ol>
<p>可以看到限制还是比较多的，如果要使用这种形式的话，在项目中推荐把文件放在静态文件夹中，打包的时候直接拷贝进去，这样我们就可以拿到固定的链接了，</p>
</li>
<li><p>字符串形式：</p>
 <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> data = <span class="string">`</span></span><br><span class="line"><span class="string">    //  worker线程 do something</span></span><br><span class="line"><span class="string">    `</span>;</span><br><span class="line"><span class="comment">// 转成二进制对象</span></span><br><span class="line"><span class="keyword">const</span> blob = <span class="keyword">new</span> Blob([data]);</span><br><span class="line"><span class="comment">// 生成url</span></span><br><span class="line"><span class="keyword">const</span> url = <span class="built_in">window</span>.URL.createObjectURL(blob);</span><br><span class="line"><span class="comment">// 加载url</span></span><br><span class="line"><span class="keyword">const</span> worker = <span class="keyword">new</span> Worker(url);</span><br></pre></td></tr></table></figure>
<p> <a href="https://codepen.io/OBKoro1/pen/JevMZY?editors=1000" target="_blank" rel="noopener">栗子</a>中就是使用这种形式的，方便我们演示。</p>
<p> 在项目中：我们可以把worker线程的逻辑写在js文件里面，然后字符串化，然后再export、import，配合webpack进行模块化管理,这样就很容易使用了。</p>
</li>
</ol>
<h3 id="主线程的其他-API："><a href="#主线程的其他-API：" class="headerlink" title="主线程的其他 API："></a>主线程的其他 API：</h3><h4 id="1-主线程与-worker-线程通信"><a href="#1-主线程与-worker-线程通信" class="headerlink" title="1. 主线程与 worker 线程通信:"></a>1. 主线程与 worker 线程通信:</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">worker.postMessage(&#123;</span><br><span class="line">  hello: [<span class="string">'hello'</span>, <span class="string">'world'</span>]</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>它们<strong>相互之间的通信可以传递对象和数组</strong>，这样我们就可以根据相互之间传递的信息来进行一些操作，比如可以设置一个<code>type</code>属性，当值为<code>hello</code>时执行什么函数，当值为<code>world</code>的时候执行什么函数。</p>
<p>值得注意的是：它们之间通信是通过拷贝的形式来传递数据的，进行传递的对象需要经过序列化，接下来在另一端还需要反序列化。这就意味着：</p>
<ol>
<li><strong>我们不能传递不能被序列化的数据</strong>，比如函数，会抛出错误的。</li>
<li>在一端改变数据，另外一端不会受影响，因为数据不存在引用，是拷贝过来的。</li>
</ol>
<h4 id="2-监听-worker-线程返回的信息"><a href="#2-监听-worker-线程返回的信息" class="headerlink" title="2. 监听 worker 线程返回的信息"></a>2. 监听 worker 线程返回的信息</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">worker.onmessage = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'父进程接收的数据：'</span>, e.data);</span><br><span class="line">    <span class="comment">// doSomething();</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="3-主线程关闭-worker-线程"><a href="#3-主线程关闭-worker-线程" class="headerlink" title="3. 主线程关闭 worker 线程"></a>3. 主线程关闭 worker 线程</h4><p>Worker 线程一旦新建成功，就会始终运行，这样有利于随时响应主线程的通信。</p>
<p>这也是 Worker 比较耗费计算机的计算资源(<code>CPU</code>)的原因，一旦使用完毕，就应该关闭 worker 线程。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">worker.terminate(); <span class="comment">// 主线程关闭worker线程</span></span><br></pre></td></tr></table></figure>
<h4 id="4-监听错误"><a href="#4-监听错误" class="headerlink" title="4. 监听错误"></a>4. 监听错误</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// worker线程报错</span></span><br><span class="line">worker.onerror = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// e.filename - 发生错误的脚本文件名；e.lineno - 出现错误的行号；以及 e.message - 可读性良好的错误消息</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'onerror'</span>, e);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>也可以像我给出的<a href="https://codepen.io/OBKoro1/pen/JevMZY?editors=1000" target="_blank" rel="noopener">栗子</a>一样,把两个报错放在一起写，有报错把信息传出来就好了。</p>
<hr>
<h2 id="Worker-线程"><a href="#Worker-线程" class="headerlink" title="Worker 线程"></a>Worker 线程</h2><h3 id="self-代表-worker-进程自身"><a href="#self-代表-worker-进程自身" class="headerlink" title="self 代表 worker 进程自身"></a>self 代表 worker 进程自身</h3><p>worker 线程的执行上下文是一个叫做<code>WorkerGlobalScope</code>的东西跟主线程的上下文(window)不一样。</p>
<p>我们可以使用<code>self</code>/<code>WorkerGlobalScope</code>来访问全局对象。</p>
<h3 id="监听主线程传过来的信息："><a href="#监听主线程传过来的信息：" class="headerlink" title="监听主线程传过来的信息："></a>监听主线程传过来的信息：</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">self.onmessage = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'主线程传来的信息：'</span>, e.data);</span><br><span class="line">    <span class="comment">// do something</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h3 id="发送信息给主线程"><a href="#发送信息给主线程" class="headerlink" title="发送信息给主线程"></a>发送信息给主线程</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">self.postMessage(&#123;</span><br><span class="line">    hello: [ <span class="string">'这条信息'</span>, <span class="string">'来自worker线程'</span> ]</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="worker-线程关闭自身"><a href="#worker-线程关闭自身" class="headerlink" title="worker 线程关闭自身"></a>worker 线程关闭自身</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">self.close()</span><br></pre></td></tr></table></figure>
<h3 id="worker-线程加载脚本："><a href="#worker-线程加载脚本：" class="headerlink" title="worker 线程加载脚本："></a>worker 线程加载脚本：</h3><p>Worker 线程能够访问一个全局函数 imprtScripts()来引入脚本，该函数接受 0 个或者多个 URI 作为参数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">importScripts(<span class="string">'http~.js'</span>,<span class="string">'http~2.js'</span>);</span><br></pre></td></tr></table></figure>
<ol>
<li><p>脚本中的全局变量都能被 worker 线程使用。</p>
</li>
<li><p>脚本的下载顺序是不固定的，但执行时会按照传入 importScripts() 中的文件名顺序进行，这个过程是同步的。</p>
</li>
</ol>
<h3 id="Worker-线程限制"><a href="#Worker-线程限制" class="headerlink" title="Worker 线程限制"></a>Worker 线程限制</h3><p>因为 worker 创造了另外一个线程，不在主线程上，相应的会有一些限制，我们无法使用下列对象：</p>
<ol>
<li>window 对象</li>
<li>document 对象</li>
<li>DOM 对象</li>
<li>parent 对象</li>
</ol>
<p><strong>我们可以使用下列对象/功能</strong>：</p>
<ol>
<li><p>浏览器：navigator 对象</p>
</li>
<li><p>URL：location 对象，只读</p>
</li>
<li><p>发送请求：XMLHttpRequest 对象</p>
</li>
<li><p>定时器：setTimeout/setInterval，在 worker 线程轮询也是很棒！</p>
</li>
<li><p>应用缓存：Application Cache</p>
</li>
</ol>
<hr>
<h3 id="多个-worker-线程"><a href="#多个-worker-线程" class="headerlink" title="多个 worker 线程"></a>多个 worker 线程</h3><ol>
<li><p><strong>在主线程内可以创建多个 worker 线程</strong></p>
<p><a href="https://codepen.io/OBKoro1/pen/JevMZY?editors=1010" target="_blank" rel="noopener">栗子</a>最下方有。</p>
</li>
<li><p><strong>worker 线程内还可以新建 worker 线程，使用同源的脚本文件创建</strong>。</p>
<p>在 worker 线程内再新建 worker 线程就不能使用<code>window.URL.createObjectURL(blob)</code>，需要使用同源的脚本文件来创建新的 worker 线程，因为我们无法访问到<code>window</code>对象。</p>
<p>这里不方便演示，跟在主线程创建 worker 线程是一个套路，只是改成了脚本文件形式创建 worker 线程。</p>
</li>
</ol>
<h3 id="线程间转移二进制数据"><a href="#线程间转移二进制数据" class="headerlink" title="线程间转移二进制数据"></a>线程间转移二进制数据</h3><p>因为主线程与 worker 线程之间的通信是拷贝关系，当我们要传递一个巨大的二进制文件给 worker 线程处理时(worker 线程就是用来干这个的)，这时候使用拷贝的方式来传递数据，无疑会造成性能问题。</p>
<p><strong>幸运的是，Web Worker 提供了一中转移数据的方式，允许主线程把二进制数据直接转移给子线程</strong>。这种方式比原先拷贝的方式，有巨大的性能提升。</p>
<p><strong>一旦数据转移到其他线程，原先线程就无法再使用这些二进制数据了，这是为了防止出现多个线程同时修改数据的麻烦局面</strong></p>
<p>下方栗子出自<a href="https://juejin.im/post/59c1b3645188250ea1502e46#comment" target="_blank" rel="noopener">浅谈 HTML5 Web Worker</a></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建二进制数据</span></span><br><span class="line"><span class="keyword">var</span> uInt8Array = <span class="keyword">new</span> <span class="built_in">Uint8Array</span>(<span class="number">1024</span>*<span class="number">1024</span>*<span class="number">32</span>); <span class="comment">// 32MB</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; uInt8Array .length; ++i) &#123;</span><br><span class="line">    uInt8Array[i] = i;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(uInt8Array.length); <span class="comment">// 传递前长度:33554432</span></span><br><span class="line"><span class="comment">// 字符串形式创建worker线程</span></span><br><span class="line"><span class="keyword">var</span> myTask = <span class="string">`</span></span><br><span class="line"><span class="string">    onmessage = function (e) &#123;</span></span><br><span class="line"><span class="string">        var data = e.data;</span></span><br><span class="line"><span class="string">        console.log('worker:', data);</span></span><br><span class="line"><span class="string">    &#125;;</span></span><br><span class="line"><span class="string">`</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> blob = <span class="keyword">new</span> Blob([myTask]);</span><br><span class="line"><span class="keyword">var</span> myWorker = <span class="keyword">new</span> Worker(<span class="built_in">window</span>.URL.createObjectURL(blob));</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用这个格式(a,[a]) 来转移二进制数据</span></span><br><span class="line">myWorker.postMessage(uInt8Array.buffer, [uInt8Array.buffer]); <span class="comment">// 发送数据、转移数据</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(uInt8Array.length); <span class="comment">// 传递后长度:0，原先线程内没有这个数据了</span></span><br><span class="line"><span class="string">``</span><span class="string">`    </span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&gt; 二进制数据有：File、Blob、ArrayBuffer 等类型，也允许在 worker 线程之间发送，**这对于影像处理、声音处理、3D 运算等就非常方便了，不会产生性能负担**</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">### 应用场景：</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">1. 数学运算</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">2. 图像、影音等文件处理</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">3. 大量数据检索</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">   比如用户输入时，我们在后台检索答案，或者帮助用户联想，纠错等操作.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">4. 耗时任务都丢到 webworker 解放我们的主线程。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">### 兼容：</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">没有找到具体的制定日期，有篇博客是在 10 年的 7 月份写的，也就是说 web worker 至少出现了八年了，以下兼容摘自[MDN](https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Workers_API/Using_web_workers)：</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">Chrome：4, Firefox：3.5, IE：10.0, Opera：10.6, Safari：4</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">现在兼容还是做的比较好的，如果实在不放心的话：</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">`</span><span class="string">``</span>js</span><br><span class="line"><span class="keyword">if</span> (<span class="built_in">window</span>.Worker) &#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="结语："><a href="#结语：" class="headerlink" title="结语："></a>结语：</h2><p>Web Worker的出现，给浏览器带来了后台计算的能力，把耗时的任务分配给worker线程来做，在很大程度上缓解了主线程UI渲染阻塞的问题，提升页面性能。</p>
<p>使用起来也不复杂，以后有复杂的问题，记得要丢给我们浏览器的后台(web worker)来处理</p>
<p>看完之后，一定要研究一下文中的栗子，自己鼓捣鼓捣，实践出真知！</p>
<p>PS: 推荐一下我上个月写的<a href="https://juejin.im/post/5bcad1326fb9a05cda779d0b" target="_blank" rel="noopener">手摸手教你使用WebSocket</a>，感兴趣的可以看一下。</p>
<h3 id="希望看完的朋友可以点个喜欢-关注，您的支持是对我最大的鼓励。"><a href="#希望看完的朋友可以点个喜欢-关注，您的支持是对我最大的鼓励。" class="headerlink" title="希望看完的朋友可以点个喜欢/关注，您的支持是对我最大的鼓励。"></a>希望看完的朋友可以点个喜欢/关注，您的支持是对我最大的鼓励。</h3><p><a href="http://obkoro1.com/" target="_blank" rel="noopener">博客</a>、<a href="http://obkoro1.com/web_accumulate/accumulate/" target="_blank" rel="noopener">前端积累文档</a>、<a href="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1631b6f52f7e7015.jpeg?raw=true" target="_blank" rel="noopener">公众号</a>、<a href="https://github.com/OBKoro1" target="_blank" rel="noopener">GitHub</a></p>
<p> 以上2018.11.25</p>
<p> 参考资料：</p>
<p> <a href="https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Workers_API/Using_web_workers" target="_blank" rel="noopener">MDN</a></p>
<p> <a href="http://www.ruanyifeng.com/blog/2018/07/web-worker.html" target="_blank" rel="noopener">Web Worker 使用教程</a></p>
<p> <a href="https://juejin.im/post/59c1b3645188250ea1502e46" target="_blank" rel="noopener">浅谈HTML5 Web Worker</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>听说，打赏我的人最后都找到了真爱。</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/weixin.jpg" alt="OBKoro1 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/ali.jpg" alt="OBKoro1 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Html5/" rel="tag"><i class="fa fa-tag"></i> Html5</a>
          
            <a href="/tags/WebWorker/" rel="tag"><i class="fa fa-tag"></i> WebWorker</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/11/一份超级详细的Vue-cli3-0使用教程/" rel="next" title="一份超级详细的Vue-cli3.0使用教程">
                <i class="fa fa-chevron-left"></i> 一份超级详细的Vue-cli3.0使用教程
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/12/02/网页全屏模式轻松掌握-局部元素全屏展示/" rel="prev" title="网页全屏模式轻松掌握[局部元素全屏展示]">
                网页全屏模式轻松掌握[局部元素全屏展示] <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          
            <img class="site-author-image" itemprop="image"
              src="/uploads/hand1.jpg"
              alt="OBKoro1" />
          
            <p class="site-author-name" itemprop="name">OBKoro1</p>
            <p class="site-description motion-element" itemprop="description">种一棵树最好的时间是十年前,其次是现在</p>
        </div>

        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives">
            
                <span class="site-state-item-count">105</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">20</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">74</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/OBKoro1" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>GitHub</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/58714f0eb123db4a2eb95372" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-globe"></i>掘金</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://obkoro1.com/web_accumulate/" target="_blank" title="前端积累">
                  
                    <i class="fa fa-fw fa-globe"></i>前端积累</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://segmentfault.com/u/obkoro1/articles" target="_blank" title="segmentfault">
                  
                    <i class="fa fa-fw fa-globe"></i>segmentfault</a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#场景"><span class="nav-number">1.</span> <span class="nav-text">场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#WebWorker-的作用：创建-worker-线程"><span class="nav-number">2.</span> <span class="nav-text">WebWorker 的作用：创建 worker 线程</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#主线程"><span class="nav-number"></span> <span class="nav-text">主线程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#我们先来看一下栗子："><span class="nav-number">1.</span> <span class="nav-text">我们先来看一下栗子：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建-worker-对象："><span class="nav-number">2.</span> <span class="nav-text">创建 worker 对象：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#主线程的其他-API："><span class="nav-number">3.</span> <span class="nav-text">主线程的其他 API：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-主线程与-worker-线程通信"><span class="nav-number">3.1.</span> <span class="nav-text">1. 主线程与 worker 线程通信:</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-监听-worker-线程返回的信息"><span class="nav-number">3.2.</span> <span class="nav-text">2. 监听 worker 线程返回的信息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-主线程关闭-worker-线程"><span class="nav-number">3.3.</span> <span class="nav-text">3. 主线程关闭 worker 线程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-监听错误"><span class="nav-number">3.4.</span> <span class="nav-text">4. 监听错误</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Worker-线程"><span class="nav-number"></span> <span class="nav-text">Worker 线程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#self-代表-worker-进程自身"><span class="nav-number">1.</span> <span class="nav-text">self 代表 worker 进程自身</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#监听主线程传过来的信息："><span class="nav-number">2.</span> <span class="nav-text">监听主线程传过来的信息：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#发送信息给主线程"><span class="nav-number">3.</span> <span class="nav-text">发送信息给主线程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#worker-线程关闭自身"><span class="nav-number">4.</span> <span class="nav-text">worker 线程关闭自身</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#worker-线程加载脚本："><span class="nav-number">5.</span> <span class="nav-text">worker 线程加载脚本：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Worker-线程限制"><span class="nav-number">6.</span> <span class="nav-text">Worker 线程限制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#多个-worker-线程"><span class="nav-number">7.</span> <span class="nav-text">多个 worker 线程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程间转移二进制数据"><span class="nav-number">8.</span> <span class="nav-text">线程间转移二进制数据</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结语："><span class="nav-number"></span> <span class="nav-text">结语：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#希望看完的朋友可以点个喜欢-关注，您的支持是对我最大的鼓励。"><span class="nav-number">1.</span> <span class="nav-text">希望看完的朋友可以点个喜欢/关注，您的支持是对我最大的鼓励。</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 &mdash; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">OBKoro1</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">
      156.0k
    </span>
  
</div>




<div>
<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span class="site-uv"><i class="fa fa-user"></i> 访问用户： <span class="busuanzi-value" id="busuanzi_value_site_uv">21621</span> 人 </span>
<span class="site-pv"><i class="fa fa-eye"></i> 访问次数： <span class="busuanzi-value" id="busuanzi_value_site_pv">68503</span> 次</span>

</div>



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  








  



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("9ANFp60h6oVyxIPGlau3NOA4-gzGzoHsz", "tMdNuKMbFtN4QsekeNVu83TV");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>

